<?php
	App::import('Model','Eav.AbstractField');
	class UserField extends AbstractField
	{
		var $name = "UserField";
		protected $fieldsetModelName = "Eav.Fieldset";
		protected $schemModels = array("Users.User");
		function useFieldset()
		{
			return false;
		}
		
		function getGroupTypes()
		{
			$group = array('register'=>__("Show On Register"),'edit'=>__("Show on edit profile"),'index'=>__("Show on admin index"));
			return $group;
		}
		
		function getAsFieldProperties()
		{
			$fields = $this->find('all',array('order'=>"UserField.order ASC"));
			$fieldProperites = array();
			$fieldProperties = array();
			foreach($fields as $field)
			{
				$field = $field[$this->alias];
				$name = $field['name'];
				unset($field['name'],$field['id']);
				$fieldProperties[$name] = $field;
			}
			return $fieldProperties;
		}
		
		function initialize()
		{
			parent::initialize();
			$this->setFieldProperties('group',array('group'=>array(),'options'=>array()));
			$this->setFieldProperties('signup',array('group'=>array('grid','add','edit'),'type'=>'checkbox','label'=>"Show on register.",'options'=>array(__('No'),__('Yes'))));
			$this->setFieldProperties('index',array('group'=>array('grid','add','edit'),'type'=>'checkbox','label'=>"Show on admin index.",'options'=>array(__('No'),__('Yes'))));
			$this->setFieldProperties('edit',array('group'=>array('grid','add','edit'),'type'=>'checkbox','label'=>"Show on edit Profile.",'options'=>array(__('No'),__('Yes'))));
		}
		/**
		 * Reutrn name of schema fields that we will be used in group.
		 */
		function getGroupFields()
		{
			return array('signup','edit','index');
		}
		/**
		 * set group array from fields values
		 * @param $value
		 * @param $action
		 * @param $result
		 * @param $fieldName
		 */
		function toggleSerialized($value,$action,$result,$fieldName)
		{
			if($action==self::READ && $fieldName=='group')
			{
				$value = array();
				$groupFields = $this->getGroupFields();
				foreach($groupFields as $field)
				{
					if(isset($result[$this->alias][$field]) && $result[$this->alias][$field] == 1)
					{
						$value[] = $field;
					}
				}
				return $value;		 
			}
			return parent::toggleSerialized($value,$action,$result,$fieldName);
		}
		
		function getFieldTypes()
		{
			$fields = array('datePicker'=>__("Date Picker"),'countrySuggestor' => __('Country'));
			$fields = am(parent::getFieldTypes(),$fields);
			unset($fields['currency'],$fields['date'],$fields['datetime']);
			asort($fields,SORT_STRING);
			return $fields;
		}
		/**
		 * deletes values from db for given field to be called on delete only
		 * @param unknown_type $fieldId
		 */
		private function deleteEavRecordsValues($fieldId)
		{
			$type = $this->field('type',array('id'=>$fieldId));
			$field = $this->field('name',array('id'=>$fieldId));
			$dbType = Utility::getDbFieldType($type);
			if($dbType)
			{
				$UserModel = cri('Users.User');
				$EavRecord = cri('Eav.EavRecord');
				$SubValueModel = $EavRecord->getValuesSubModel($dbType);
				$eavRecordIds =  $EavRecord->find('list',array('conditions'=>array('entity'=>array($UserModel->alias)),'fields'=>array('id')));
				if($eavRecordIds)
				{
					$e = $SubValueModel->deleteAll(array(
						$SubValueModel->alias.'.eav_record_id' => $eavRecordIds,
						$SubValueModel->alias.'.field' => $field,
						));
				}
			}
		}
		
		function beforeDelete($cascade)
		{
			$return = parent::beforeDelete($cascade);
			if($return == true)
			{
				$db =& ConnectionManager::getDataSource($this->useDbConfig);
				//begin transactions for delete Eav Records Value
				$db->begin($this);
				$this->deleteEavRecordsValues($this->id);	
			}
			return $return;
		}
		
		function afterDelete()
		{
			$db =& ConnectionManager::getDataSource($this->useDbConfig);
			//commit transactions for delete Eav Records Value
			$db->commit($this);
			Cache::delete('user_fieldproperties');
			cri('Users.User')->deleteCustomFieldCache();
			return parent::afterDelete();
		}
		
		function afterSave($created)
		{
			cri('Users.User')->deleteCustomFieldCache();
			parent::afterSave($created);
		}
		//@FBCONNECT INTERACTION
		function getFacebookFields()
		{
			$fields = array('first_name','last_name',"name","bio","birthday","website","hometown","gender",'picture');
			return array_combine($fields,$fields);
		}
		//@FBCONNECT INTERACTION
		function getFieldsForFacebook()
		{
			$fieldTypes = $this->getFieldTypes();
			$userFields = $this->find("all",array("recursive"=>-1));
			$userFieldsToReturn = array();
			foreach ($userFields as $userField)
			{
				$userFieldsToReturn[$userField[$this->alias]['name']] = $userField[$this->alias]['label'].'('.$fieldTypes[$userField[$this->alias]['type']].')';
			}
			$userFieldsToReturn["avatar"] = "avatar(Upload Field)";
			return $userFieldsToReturn;
		}
	}
?>